#include "controller.h"
#include "ball.h"
#include <QPainter>

#include <QGraphicsEllipseItem>

Controller::Controller() :
    QGraphicsScene()
{
    cells.resize(3 * fieldSize);
    isField.resize(3 * fieldSize);
    for(size_t i = 0; i < cells.size(); ++i)
    {
        cells[i].assign(cells.size(), 0);
        cells[i].assign(cells.size(), false);
    }
    for(size_t i = 1; i < cells.size() - 1; ++i)
        for(size_t j = 1; j < cells.size() - 1; ++j)
        {
            if ((i < fieldSize && j < fieldSize) || (i >= 2 * fieldSize && j < fieldSize) ||
                    (i >= 2 * fieldSize && j >= 2 * fieldSize) || (i < fieldSize && j >= 2 * fieldSize)
                    || (i == fieldSize * 3 / 2 && j == fieldSize * 3 / 2))
            {
                isField[i][j] = false;
                cells[i][j] = 0;
            }
            else
            {
                Ball* ell = new Ball(i * cellSize + 1, j * cellSize + 1, cellSize - 2, cellSize - 2, &cells, &isField);
                addItem(ell);
                isField[i][j] = true;
                cells[i][j] = ell;
            }
        }
    isField[fieldSize * 3 / 2][fieldSize * 3 / 2] = true;
}

void Controller::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->setPen(Qt::black);
    int ballsNumber = 0;
    for(size_t i = 1; i < cells.size() - 1; ++i)
        for(size_t j = 1; j < cells.size() - 1; ++j)
        {
            if (cells[i][j]) ballsNumber++;
            if ((i < fieldSize && j < fieldSize) || (i >= 2 * fieldSize && j < fieldSize) ||
                    (i >= 2 * fieldSize && j >= 2 * fieldSize) || (i < fieldSize && j >= 2 * fieldSize))
            {
            }
            else
            {
                painter->drawRect(i * cellSize, j * cellSize, cellSize, cellSize);
            }
        }
     emit updateScore(fieldSize * fieldSize * 5 - 1 - fieldSize * 4 - ballsNumber);

     QGraphicsScene::drawBackground(painter, rect);
}
